//
//  FilterCarCell.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/2/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit
import SnapKit


final class FilterCarCell: UITableViewCell, ConfigurableCell {
    
    // MARK: - Outlets

    lazy private var parameterView: ParametersView = {
       let view = ParametersView()
       view.delegate = self
       return view
    }()
    
    // MARK: - Properties
    
    private var index: Int!
    private var carFilterModel: CarFilterModel!
    private var data: Filter.FilterCar?
    
    // MARK: - Init
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.addViews()
        NotificationCenter.default.addObserver(self, selector: #selector(putMarkModel(notification:)), name: NSNotification.Name(rawValue: "putMarkModel"), object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "putMarkModel"), object: nil)
    }

    
    // MARK: - Methods
    
    func configure(data object: Filter.FilterCar, index: Int) {
        self.index = index
        if self.data == nil {
            self.data = object
            self.setUpParameterView()
        }
    }
    func returnData() -> Filter.FilterCar {
        return Filter.FilterCar(carParameters: carFilterModel.carFilter)
    }
}

extension FilterCarCell {
    @objc private func putMarkModel (notification: NSNotification) {
        if let userInfo = notification.userInfo {
            if let data = userInfo["data"] as? CarFilter, let _ = userInfo["type"] as? MarkaModelMode {
                carFilterModel = CarFilterModel(carFilter: data)
                let parameters = carFilterModel.inputs.map {
                    x in ParametersViewModel(input: x)
                }
                parameterView.items = parameters
            }
        }
    }
}


// MARK: - Methods

extension FilterCarCell {
    private func setUpParameterView() {
        
        if let carParameters = data!.carParameters {
            carFilterModel = CarFilterModel(carFilter: carParameters)
        } else {
            carFilterModel = CarFilterModel(carFilter: CarFilter(marka: nil, models: []))
        }
        
        let parameters = carFilterModel.inputs.map {
            x in ParametersViewModel(input: x)
        }
        parameterView.items = parameters
    }
}


// MARK: - Adding views to superview

extension FilterCarCell {
    
    private func addViews () {
        self.contentView.backgroundColor = .whiteBlueColor
        self.contentView.addSubview(parameterView)
        self.applyConstraints()
    }
    
    private func applyConstraints() {
        parameterView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(20)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(-20)
        }
    }
}

extension FilterCarCell: ParametersViewDelegate {
    
    func didSelectParameter(item: ParametersViewModel) {
        
        var userInfo = ["item": item, "cell": self, "index": index as Any, "isClick": true as Any] as [String : Any]
        
        if item.type == "model" {
            userInfo["marka"] = carFilterModel.carFilter.marka
        }
        
        if item.type == "generation" {
            var _models:[Model] = []
            for (_, model) in self.carFilterModel.carFilter.models.enumerated() {
                var _model = model
                _model.generation = nil
                _models.append(_model)
            }
            userInfo["models"] = _models
        }
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "handleCell"), object: nil, userInfo: userInfo)
    }
    
    /// Parameter View Reset Button clicked
    /// - Parameters:
    ///   - value: String Text Value of Field
    ///   - placeholder: Hint of Field
    ///   - itemIndex: index of item in view
    func didClearValue(value: String?, placeholder: String, itemIndex: Int) {
        
        var userInfo = ["isClick": false] as [String : Any]
        
        if itemIndex == 2 {

            // Remove Generations

            var carFilter = carFilterModel.carFilter
            var models: [Model] = []

            for model in carFilter.models {
                var _model = model
                _model.generation = nil
                models.append(_model)
            }
            carFilter.models = models
        } else if itemIndex == 1 {

            // Remove Models

            carFilterModel.carFilter.models = []
        } else if itemIndex == 0 {

            // Remove Marks

            carFilterModel.carFilter.marka = nil
            carFilterModel.carFilter.models = []
        }

        let parameters = carFilterModel.inputs.map {
            x in ParametersViewModel(input: x)
        }
        parameterView.items = parameters
        userInfo["items"] = parameters
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "handleCell"), object: nil, userInfo: userInfo)
    }
}
